import { defineStore } from "pinia";
import axios from "axios";
import { getUserInfo, getUserMenu, getPerms } from "@/services/api/account";

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const AuthStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: "AuthState",
  // state: 返回对象的函数
  state: () => ({
    access_token: "",
    refresh_token: "",
    user: {
      dept: {},
      roles: [],
    },
    menus: [],
    perms: [],
    login: false,
  }),
  getters: {},
  actions: {
    // 获取用户信息，包含（基本信息，菜单，顶级菜单）
    getUserInfo() {
      return new Promise((resolve, reject) => {
        axios
          .all([getUserInfo(), getUserMenu()])
          .then(
            axios.spread((userData: any, menusData: any) => {
              this.user = userData.data;
              this.menus = menusData.data;

              resolve({
                user: userData.data,
                menus: menusData.data,
              });
            })
          )
          .catch((err: any) => {
            reject(err);
          });
      });
    },
    // 设置路由信息
    updatePerms() {
      return new Promise((resolve, reject) => {
        getPerms()
          .then((res: any) => {
            console.log("res");
            console.log(res);
            const params = res.data;
            this.user = params.user;
            this.menus = params.menus;
            this.perms = params.perms;
            this.login = true;
            resolve(res);
          })
          .catch((err: any) => {
            reject(err);
          });
      });
    },
    userLogin(data: unknown) {
      return new Promise((resolve, reject) => {
        getPerms()
          .then((res: any) => {
            console.log("res");
            console.log(res);
            resolve(data);
          })
          .catch((err: any) => {
            reject(err);
          });
      });
    },
  },
});
